package joodle.domain;

import static java.lang.Math.max;
import static java.lang.Math.min;

import java.awt.geom.Path2D;
import java.awt.geom.Rectangle2D;

/**
 * The other basic shape included in joodle out of box. It is a subclass of 
 * AbstractShape and inherits most of its methods. The draw, hasEnoughPoints, isPointOn 
 * and asXML methods will be overridden in these basic shapes classes to give the proper 
 * functionality to each of the basic shapes.
 */

public class Rectangle extends AbstractShape {

	public Rectangle() {
	}
	
	protected Rectangle(Rectangle r) {
		super(r);
	}

	/**
	 * Creates an AWT version of the Rectangle
	 * @see AbstractShape#remakeAwtShape()
	 */
	@Override
	protected void remakeAwtShape() {
		Point p1 = points.get(0);
		Point p2 = points.get(1);
		float xMin = Math.min(p1.getX(), p2.getX());
		float yMin = Math.min(p1.getY(), p2.getY());
		float xMax = Math.max(p1.getX(), p2.getX());
		float yMax = Math.max(p1.getY(), p2.getY());
		path = new Path2D.Float(new Rectangle2D.Float(xMin, yMin, xMax - xMin, yMax - yMin));	
	}
	
	/**
	 * Checks if there are enough points to create a Rectangle object
	 * @see Shape#hasEnoughPoints(Point p)
	 * @return a boolean value depends on the enough points condition
	 */
	@Override
	public boolean hasEnoughPoints() {
		return points.size() > 1;
	}

	/**
	 * Updates the last point of the Rectangle object
	 * @param p the point to be updated
	 * @see Shape#updateEndPoint(Point p)
	 */
	@Override
	public void updateEndPoint(Point p) {
		if(!hasEnoughPoints())
			return;
		points.set(1, p);
		remakeAwtShape();
	}

	/**
	 * Creates a clone of the Rectangle shape
	 * @see Shape#cloneShape()
	 * @return a new Rectangle shape
	 */
	@Override
	public Shape cloneShape() {
		return new Rectangle(this);
	}

	/**
	 * Creates a character sequence which is the XML representation of the Rectangle
	 * @return string includes XML representation of the Rectangle
	 * @see Shape#asXML()
	 */
	@Override
	public String asXML() {
		StringBuilder sb = new StringBuilder();

		Point p1 = points.get(0);
		Point p2 = points.get(1);
		double x = min(p1.getX(), p2.getX()); 
		double y = min(p1.getY(), p2.getY());
		double width = max(p1.getX(), p2.getX()) - min(p1.getX(), p2.getX());
		double height = max(p1.getY(), p2.getY()) - min(p1.getY(), p2.getY());
		
		sb.append(String.format("<rect x=\"%f\" y=\"%f\" width=\"%f\" height=\"%f\"",
				x, y, width, height));
		
		sb.append(attributesAsXML());
		sb.append(transformAsXML());
		
		sb.append(" />\n");

		return sb.toString();
	}

}
